import os
import shutil
import fitz
from MyQR import myqr


def generatePDF(stuInfo, pdfPath, DEBUG):
    tmpPath = os.path.join(os.getcwd(), 'tmp')
    if not os.path.exists(tmpPath):
        os.mkdir(tmpPath)
    generateQR(stuInfo, tmpPath, DEBUG)  # 生成二维码
    makePDF(stuInfo, tmpPath, pdfPath)  # 生成pdf
    # 清空临时文件夹内容及临时文件夹
    if not DEBUG:
        shutil.rmtree(tmpPath)


def generateQR(stuInfo, tmpPath, DEBUG):  # 生成二维码
    if DEBUG:
        print('start generateQR()')
    i = 0
    stuLen = len(stuInfo)
    for stu in stuInfo:
        i += 1
        print('\r绘制二维码中{}/{}\t'.format(i, stuLen), end='')
        myqr.run(words=stu['id'],
                 version=1,
                 level='H',
                 save_name=stu['id']+'.png',
                 save_dir=tmpPath)
    if DEBUG:
        print('done generateQR()')


def makePDF(stuInfo, tmpPath, pdfPath):  # 生成pdf
    doc = fitz.open()
    paperWidth = 595  # 纸张宽
    paperHeight = 842  # 纸张高
    stuInRow = 7  # 每行7人
    stuInColumn = 7  # 每列7人
    stuPerPage = stuInRow * stuInColumn  # 每页学生个数
    singleStuWidth = paperWidth/stuInRow  # 单个学生所占空间宽
    singleStuHeight = paperHeight/stuInColumn  # 单个学生所占空间高
    stuCount = 0
    for i in range(len(stuInfo)):
        for j in range(stuInfo[i]['num']):
            if stuCount % stuPerPage == 0:  # 需要添加新页
                page = doc.new_page(-1,
                                    width=paperWidth,
                                    height=paperHeight)
            x = (stuCount % 7) * singleStuWidth
            y = ((stuCount // 7) % 7) * singleStuHeight
            page.insert_image(fitz.Rect(x, y, x+singleStuWidth, y+singleStuWidth),
                              filename=os.path.join(tmpPath, stuInfo[i]['id']+'.png'),
                              overlay=False)
            page.insert_textbox(fitz.Rect(x, y+singleStuWidth, x+singleStuWidth,
                                          y+singleStuHeight-(singleStuHeight-singleStuWidth)/2),
                                stuInfo[i]['id'],
                                fontname='helv',
                                fontsize=8,
                                align=1)
            page.insert_textbox(fitz.Rect(x, y+singleStuHeight-(singleStuHeight-singleStuWidth)/2-8,
                                          x+singleStuWidth, y+singleStuHeight),
                                stuInfo[i]['name'],
                                fontname='china-s',
                                fontsize=8,
                                align=1)
            stuCount += 1
            if stuCount % stuPerPage == 0 or stuCount == len(stuInfo):  # 马上要添加新页了，划线
                shape = page.new_shape()
                # 横线
                for k in range(1, stuInColumn):
                    shape.draw_line((0, k*singleStuHeight), (paperWidth, k*singleStuHeight))
                # 竖线
                for k in range(1, stuInRow):
                    shape.draw_line((k*singleStuWidth, 0), (k*singleStuWidth, paperHeight))
                shape.finish(width=0.5,
                             dashes='[5 10] 0')
                shape.commit()
    doc.save(pdfPath)


if __name__ == '__main__':
    tmpPath1 = os.getcwd() + '/tmp'
    if not os.path.exists(tmpPath1):
        os.mkdir(tmpPath1)

